<script setup>
import inputBox from "@/components/inputBox.vue";
import decorationBox from "@/components/decorationBox.vue";
import typeInBox from "@/components/typeInBox.vue";
import hadTypInBox from "@/components/hadTypInBox.vue";
import latestUpdatedTime from "@/components/latestUpdatedTime.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { ref, onMounted, watch } from "vue";
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();

//总的记录数量
const wholeCount = ref(0)

//查询到的记录数量
const queryCount = ref(null)

//单词条目的数量
const itemCounts = ref(1)

//是否保存过的flag
const notSaved = ref(false)
const isChange = ref(false)

const searchTimeRef = ref('')
const queryTimeRef = ref('')

//查询到多条记录时的数组
const resultArray = ref([{
  word: "",
  reading: "",
  wordArray: [
    {
      type: "",
      translation: "",
      remark: ""
    }
  ],
}])

//备份查询结果数组
const resultArrayCopy = ref([{
  word: "",
  reading: "",
  wordArray: [
    {
      type: "",
      translation: "",
      remark: ""
    }
  ],
}])
//用于记录上一条查询的索引
const resultIndexCopy = ref(1)

const placeholder = ref("请输入单词");

//能否新增单词的flag
const addNewWordFlag = ref(false);

//查询后是否显示新增按钮
const afterSearch = ref(false);

//是否切换为更新按钮的flag
const isChangeToUpadateFlag = ref(false);

//json数据
const inputValue = ref({
  id: "",
  word: "",
  reading: "",
  wordArray: [
    {
      type: "",
      translation: "",
      remark: ""
    }
  ],

});

// 深度监听
watch(
  () => resultArray.value,
  (newVal) => {
    // 比较当前结果与备份是否一致
    notSaved.value = JSON.stringify(newVal) !== JSON.stringify(resultArrayCopy.value)
  },
  { deep: true }
)

//查询逻辑
const searchWords = () => {
  const userInputValue = inputValue.value.word.trim().toLowerCase()
  if (userInputValue === '') {
    ElMessageBox.alert('请输入正确的单词', '提示', {
      confirmButtonText: '确定'
    })
    return
  }
  // 重置结果
  resultArray.value = [];
  resultArrayCopy.value = [];
  queryCount.value = 0;
  afterSearch.value = true;
  addNewWordFlag.value = false;

  // 遍历所有单词，收集匹配结果
  counterStore.wholeWordList.forEach((wordObj) => {
    if (wordObj.word.toLowerCase().includes(userInputValue)) {
      // 创建深拷贝对象
      const copiedWord = JSON.parse(JSON.stringify(wordObj))
      resultArray.value.push(copiedWord)
      resultArrayCopy.value.push(JSON.parse(JSON.stringify(copiedWord)))
      queryCount.value += 1
    }
  })

  // 初始化索引
  resultIndexCopy.value = 0;
}

//按钮点击的标志，用于重新渲染界面
const isClick = ref(false);

//取消按钮的逻辑
const CancelAddWord = async () => {
  // 检查是否存在未保存修改
  if (notSaved.value) {
    try {
      // 显示确认对话框（修正按钮文本）
      await ElMessageBox.confirm(
        '存在未保存的修改，是否放弃更改？',
        '提示',
        {
          confirmButtonText: '放弃',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }
      )
      // 恢复查询结果到原始状态
      if (queryCount.value > 0) {
        resultArray.value = JSON.parse(JSON.stringify(resultArrayCopy.value))
      }
    } catch (error) {
      // 用户点击取消或关闭对话框时，直接返回不执行后续操作
      console.log('用户取消操作', error)
      return
    }
  }

  notSaved.value = false
  addNewWordFlag.value = false
  inputValue.value = {
    id: "",
    word: "",
    reading: "",
    wordArray: [{ type: "", translation: "", remark: "" }],
    remark: ""
  }
  afterSearch.value = false
  queryCount.value = 0
  itemCounts.value = 1

  // 仅在新增模式下清空结果数组
  if (addNewWordFlag.value) {
    resultArray.value = []
  }
}

//新增单词条目的逻辑
const addTranslation = () => {
  if (itemCounts.value < 4) {
    itemCounts.value += 1
    inputValue.value.wordArray.push({
      type: "",
      translation: ""
    });
    isChange.value = true;
    notSaved.value = true;
  } else {
    window.alert("最多只能添加4个类型释义");
  }
};

//新增单词条目--查询版的逻辑
const addTranslationSearch = (index) => {
  itemCounts.value = resultArray.value[index].wordArray.length;
  if (itemCounts.value < 4) {
    itemCounts.value += 1
    resultArray.value[index].wordArray.push({
      type: "",
      translation: ""
    });
    isChange.value = true;
    notSaved.value = true;
  } else {
    window.alert("最多只能添加4个类型释义");
  }
}

//删除单词条目的逻辑
const deleteTranslation = (index) => {
  if (itemCounts.value <= 1) {
    itemCounts.value = 1;
    window.alert("至少要有一个类型释义");
    return
  }
  inputValue.value.wordArray.splice(index, 1);
  itemCounts.value -= 1;
  isChange.value = true;
  notSaved.value = true;

};

//删除单词条目--查询版的逻辑
const deleteTranslationSearch = (index) => {
  // 获取当前显示的记录
  const currentRecord = resultArray.value[resultIndexCopy.value];

  // 确保存在至少一个条目
  if (currentRecord.wordArray.length <= 1) {
    window.alert("至少要有一个类型释义");
    return;
  }
  isChange.value = true;
  notSaved.value = true;
  // 删除指定索引的条目
  currentRecord.wordArray.splice(index, 1);
};

//提交单词的逻辑
const submit = async () => {
  if (inputValue.value.word === "") {
    ElMessageBox.alert('请先填写单词信息', '提示', {
      confirmButtonText: 'OK'
    })
    return;
  }
  if (inputValue.value.wordArray.type === "" || inputValue.value.wordArray.translation === "") {
    ElMessageBox.alert('请填写完整的单词类型与释义', '提示', {
      confirmButtonText: 'OK'
    })
    return;
  }

  inputValue.value.word = (inputValue.value.word).toLowerCase();

  const data = {
    word: inputValue.value.word,
    reading: inputValue.value.reading,
    wordArray: inputValue.value.wordArray,
    remark: inputValue.value.remark,
    id: (wholeCount.value + 1).toString()
  };

  const updatedTime = searchTimeRef.value.$el.innerText;
  const timeId = 1
  const timeData = {
    time: updatedTime,
  }

  try {
    const res = await axios.post("http://localhost:3000/word", data);
    const resBeforeMemery = await axios.post("http://localhost:3000/beforeMemery", data)
    const timeRes = await axios.put(`http://localhost:3000/lastUpdated/${timeId}`, timeData)
    console.log(timeRes.data);
    console.log(res.data);
    console.log(resBeforeMemery.data);
    ElMessageBox.alert('提交成功', '提示', {
      confirmButtonText: '确定'
    })
    counterStore.latesUpdatedTime = updatedTime
    afterSearch.value = false;
    addNewWordFlag.value = false;
    isChange.value = false;
    notSaved.value = false;
    setTimeout(() => {
      location.reload()
    }, 1000)
  } catch (error) {
    console.error(error)
    ElMessageBox.alert('提交失败', '错误', {
      confirmButtonText: '确定'
    })
  }
  inputValue.value.word = "";
  inputValue.value.reading = "";
  inputValue.value.wordArray = [
    {
      type: "",
      translation: ""
    }
  ];
  inputValue.value.remark = "";
  isClick.value = false;
  afterSearch.value = false;
  addNewWordFlag.value = false;
};

//切换查询结果的索引
const changeResultIndexCopy = (num) => {
  if (notSaved.value) {
    ElMessageBox.alert('请先保存或更新单词', '提示', {
      confirmButtonText: '确定'
    })
    return
  }
  if (resultIndexCopy.value + num < 0 || resultIndexCopy.value + num > resultArray.value.length - 1) {
    return
  }
  resultIndexCopy.value += num
}

//更新单词的逻辑
const updateWord = async () => {

  const updatedTime = queryTimeRef.value.$el.innerText;
  const data = {
    time: updatedTime,
  }
  try {
    // 获取要更新的记录
    const targetRecord = resultArray.value[resultIndexCopy.value]

    // 确保获取到正确的ID
    const recordId = targetRecord.id

    const timeId = 1

    // 更新本地数据
    const index = counterStore.wholeWordList.findIndex(item => item.id === recordId)
    if (index !== -1) {
      counterStore.wholeWordList[index] = { ...targetRecord }
    }

    // 发送PUT请求更新服务器数据
    const res = await axios.put(`http://localhost:3000/word/${recordId}`, targetRecord)
    const resBeforeMemery = await axios.post(`http://localhost:3000/beforeMemery`, targetRecord)
    const timeRes = await axios.put(`http://localhost:3000/lastUpdated/${timeId}`, data)
    console.log(resBeforeMemery.data);

    console.log('更新结果:', res.data, timeRes.data, resBeforeMemery.data)
    ElMessageBox.alert('更新成功', '提示', {
      confirmButtonText: '确定'
    })
    counterStore.latesUpdatedTime = updatedTime
    afterSearch.value = false;
    addNewWordFlag.value = false;
    notSaved.value = false;
  } catch (error) {
    console.error('更新失败:', error)
    ElMessageBox.alert('更新失败', '错误', {
      confirmButtonText: '确定'
    })
  }
  isClick.value = false;
}

const deleteWord = async () => {
  try {
    const targetRecord = resultArray.value[resultIndexCopy.value]
    const recordId = targetRecord.id

    await ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 并行删除请求
    const [mainRes, backupRes] = await Promise.all([
      axios.delete(`http://localhost:3000/word/${recordId}`),
      axios.delete(`http://localhost:3000/beforeMemery/${recordId}`)
    ])
    console.log(mainRes.data, backupRes.data);


    const updateStores = (store) => {
      const index = store.findIndex(item => item.id === recordId)
      if (index !== -1) {
        store.splice(index, 1)
      }
    }

    updateStores(counterStore.wholeWordList)
    updateStores(counterStore.beforeMemery)
    updateStores(resultArray.value)

    wholeCount.value = counterStore.wholeWordList.length
    queryCount.value = resultArray.value.length

    if (resultIndexCopy.value >= resultArray.value.length) {
      resultIndexCopy.value = Math.max(0, resultArray.value.length - 1)
    }

    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1000
    })

  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage({
        message: error.response?.data?.message || '删除失败',
        type: 'error',
        duration: 1000
      })
    }
  }
}

onMounted(async () => {
  try {
    //初次加载时获取所有单词
    const res0 = await axios.get("http://localhost:3000/word")
    counterStore.wholeWordList = res0.data
    console.log('res0.data[0].wordArray[0].type:', res0.data[0].wordArray[0].type);

    const res1 = await axios.get("http://localhost:3000/beforeMemery")
    counterStore.beforeMemery = res1.data
    console.log(res1.data);

    //初次加载时获取总的记录数量
    wholeCount.value = res0.data.length

    //获取最近更新时间
    const timeId = 1
    const res2 = await axios.get(`http://localhost:3000/lastUpdated/${timeId}`)
    counterStore.latesUpdatedTime = res2.data.time
    console.log('counterStore.latesUpdatedTime:', counterStore.latesUpdatedTime);

  } catch (error) {
    console.error(error)
  }
})

watch(() => {
  if (afterSearch.value == true) {
    if (queryCount.value == 0) {
      isChangeToUpadateFlag.value = false;
    }
    else {
      isChangeToUpadateFlag.value = true;
    }
  }
})

const handleKeyDown = (event) => {
  if (event.key === 'Enter') {
    searchWords()
  }
}
</script>

<template>
  <div class="wordStash-box">
    <div class="wordStashManager-box">
      <div class="title-box">
        <decorationBox></decorationBox>
        <h2 class="Feature-title">词库管理</h2>
      </div>

      <div class="main-box">
        <div class="inputArea">
          <h3 class="inside-title">单词：</h3>
          <inputBox v-model="inputValue.word" :placeholder="placeholder" @keydown="handleKeyDown"></inputBox>
          <button class="inquire-button" @click="searchWords">查询</button>
          <div class="Records" v-show="afterSearch">
            找到 {{ queryCount }} 条记录
          </div>
          <button class="add-button" v-if="afterSearch == true" @click="addNewWordFlag = true">新增</button>

          <button class="add-button" v-if="afterSearch == true && queryCount != 0"
            @click="changeResultIndexCopy(-1)">上一条</button>
          <button class="add-button" v-if="afterSearch == true && queryCount != 0"
            @click="changeResultIndexCopy(1)">下一条</button>
          <button class="add-button" v-if="afterSearch" @click="CancelAddWord">取消</button>
          <button class="add-button delete-button" v-if="afterSearch && queryCount != 0" @click="deleteWord">删除</button>
        </div>
        <div class="partingLine"></div>

        <div class="submitButton-box">
          <button class="submitButton" @click="submit" v-if="afterSearch == true && addNewWordFlag == true">提交</button>
          <button class="submitButton" @click="updateWord"
            v-if="afterSearch == true && addNewWordFlag == false && queryCount > 0">更新</button>
        </div>

        <div class="main-function-box" v-if="addNewWordFlag">
          <div class="inputRow">
            <h3 class="inside-title word">单词：{{ inputValue.word }}</h3>
            <h3 class="inside-title reading">读法：</h3>
            <inputBox v-model="inputValue.reading" :placeholder="'请输入读法'"></inputBox>
            <button class="add-item-button" @click="addTranslation">添加条目</button>
          </div>

          <div class="typeInBox" v-for="(item, index) in inputValue.wordArray" :key="index">
            <typeInBox v-model="inputValue.wordArray[index]" @delete="deleteTranslation(index)">
            </typeInBox>
          </div>
          <latestUpdatedTime ref="searchTimeRef"></latestUpdatedTime>
        </div>

        <!-- 查询结果显示 -->
        <div class="main-function-box" v-if="queryCount > 0 && !addNewWordFlag">
          <div class="inputRow">
            <h3 class="inside-title word">单词：{{ resultArray[resultIndexCopy]?.word }}</h3>
            <h3 class="inside-title reading">读法：</h3>
            <inputBox v-model="resultArray[resultIndexCopy].reading" :placeholder="'请输入读法'" />
            <button class="add-item-button" @click="addTranslationSearch(resultIndexCopy)">添加条目</button>
          </div>

          <!-- 遍历当前记录的 wordArray -->
          <div class="typeInBox" v-for="(item, index) in resultArray[resultIndexCopy]?.wordArray" :key="index">
            <typeInBox v-model="resultArray[resultIndexCopy].wordArray[index]"
              @delete="deleteTranslationSearch(index)" />
          </div>
          <latestUpdatedTime ref="queryTimeRef"></latestUpdatedTime>
        </div>

      </div>
    </div>

    <div class="hadTypeIn-box">
      <div class="title-box">
        <decorationBox></decorationBox>
        <h2 class="Feature-title">已录入单词</h2>
      </div>
      <div class="rowBox">
        <h4 class="totalWords">总数：{{ wholeCount }}</h4>
        <h4 class="latesUpdatedTime">最近更新时间：{{ counterStore.latesUpdatedTime }}</h4>
      </div>
      <el-scrollbar height="76vh" top="2vh">
        <div class="hadTypeIn-list" v-for="(item, index) in counterStore.wholeWordList" :key="index">
          <hadTypInBox :word="item.word" :wordArray="item.wordArray"></hadTypInBox>
        </div>
      </el-scrollbar>


    </div>


  </div>
</template>

<style scoped lang="scss">
.wordStash-box {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  // background-color: #a55e5e;
}

.wordStashManager-box {
  position: relative;
  width: 75%;
  height: 100%;
  border-radius: 10px;
  box-shadow: #000000 0px 2px 7px -4px;
}

.title-box {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 5vh;
  left: 1vw;
  top: 2%;
  // background-color: #734040;
}

.Feature-title {
  user-select: none;
  position: relative;
  font-size: 2rem;
  font-weight: 700;
  left: 0.6vw;
  height: 4vh;
  line-height: 4vh;
  // background-color: #b96e6e;
}

.hadTypeIn-box {
  position: relative;
  height: 100%;
  border-radius: 10px;
  width: 24.5%;
  left: 0.5%;
  box-shadow: #000000 0px 2px 7px -4px;
}

.main-box {
  position: relative;
  width: 98%;
  left: 1%;
  top: 5vh;
  height: 79.5vh;
  border-radius: 10px;
  box-shadow: #FFD978 0px 2px 6px -1px;
}

.inputArea {
  position: relative;
  width: 100%;
  top: 2vh;
  display: flex;
  align-items: center;
  flex-direction: row;
}

.inside-title {
  position: relative;
  user-select: none;
  width: 5vw;
  left: 1.5vw;
  font-size: 1.5rem;
}

.inquire-button {
  position: relative;
  width: 5vw;
  height: 3vh;
  left: 4vw;
  background-color: #FFD978;
  font-size: 1rem;
  font-weight: 600;
  color: #545353;

  border: {
    style: none;
    radius: 8px;
  }
}

.Records {
  user-select: none;
  position: relative;
  font-weight: 600;
  left: 6vw;
}

.add-button {
  position: relative;
  width: 5vw;
  height: 3vh;
  left: 8vw;
  background-color: #FFD978;
  font-size: 1rem;
  font-weight: 600;
  color: #545353;
  margin-right: 2vw;

  border: {
    style: none;
    radius: 8px;
  }
}

.button-disabled {
  background-color: #E8E8E8;
  cursor: not-allowed;
}

.partingLine {
  position: relative;
  height: 0.18vh;
  width: 96%;
  left: 2%;
  background-color: #FFD978;
  top: 5vh;
}

.submitButton-box {
  position: absolute;
  width: 100%;
  display: flex;
  bottom: 2vh;
  justify-content: center;
}

.submitButton {
  position: relative;
  width: 7vw;
  height: 3.5vh;
  background-color: #FFD978;
  font-size: 1rem;
  font-weight: 600;
  color: #545353;

  border: {
    style: none;
    radius: 8px;
  }
}

.main-function-box {
  position: relative;
  width: 100%;
  top: 8vh;
  height: 58vh;
  border-radius: 10px;
  // background-color: #351b1b;
  display: flex;
  flex-direction: column;
}

.inputRow {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

  & .word {
    position: relative;
    min-width: 10vw;
    width: auto;
    max-width: 35vw;
  }

  & .reading {
    margin-left: 2vw;
  }
}

.add-item-button {
  position: absolute;
  width: 6%;
  left: 92%;
  height: 3.5vh;
  background-color: #B1EAFF;
  font-size: 0.9rem;
  font-weight: 600;
  color: #ffffff;

  border: {
    style: none;
    radius: 8px;
  }
}

.rowBox {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  left: 1vw;
  top: 3vh;
}

.latesUpdatedTime {
  position: absolute;
  width: 100%;
  top: 79vh;
  font-size: 0.9rem;
  text-align: center;
  color: #999;
  margin-left: 10px;
  z-index: 5;
}

.hadTypeIn-list {
  position: relative;
  margin-top: 2vh;
}

.delete-button {
  position: absolute;
  margin-left: 58.5vw;
  background-color: #ffc7d4;
  width: 5vw;
}

::v-deep(.el-scrollbar__wrap) {
  position: relative;
  top: 3vh;
}
</style>
